<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>百度搜索优化之节流</title>
    <style>
        .box{
            position: relative;
            width: 244px;
            margin: 10px auto;
        }
        .box .search{
            display: flex;
        }
        input{
            outline: none;
            padding: 10px;
        }
        ul,li{
            list-style: none;
        }
        ul{
            position: absolute;
            top: 24px;
            left: 0;
            border: 1px solid #000;
            padding: 10px 0;
            display: none;
        }
        li{
            width: 240px;
            padding-left: 10px;
            margin-bottom: 5px;
        }
    </style>
</head>
<body>
    <div class="box">
        <div class="search">
            <input type="text" ><button>搜索</button>
        </div>
        <ul id='search_list'>
            <!-- <li></li> -->
        </ul>
    </div>

    <script>
        var keyword = document.querySelector('.search>input');
        var show = document.querySelector('#search_list');
        // 节流开关
        var timer = null;

        keyword.oninput = function(){
            // 当timer非空时，直接终止执行
            if(timer !== null){
                return false
            }

            var _keyword = keyword.value;

            // 延时器包裹操作
            timer = setTimeout(function(){
                timer = null;

                if(!_keyword){
                    show.style.display = 'none';
                    return false
                }

                ajax( { 
                    method : "jsonp" , 
                    url : "https://www.baidu.com/sugrec",
                    dataObj : {
                            pre:1,
                            p:3,
                            ie:"utf-8",
                            json:1,
                            prod:"pc",
                            from:"pc_web",
                            sugsid:"32218,1425,31672,32139,31254,32045,32230,32299,31639",
                            wd:_keyword,
                            req:2,
                            csor:5,
                            cb:"callback",
                            _:Date.now()
                    },
                    jsonpcallback : "callback",
                    _callback : function(data){
                        data = data.g;
                        // 数据存在则进行渲染操作，反之则直接终止
                        if(data){
                            var html = '';
                            data.forEach(({q})=>{
                                html += `
                                    <li>${q}</li>
                                `;
                            })
                            show.innerHTML = html;
                        }else{
                            return false
                        }
                        show.style.display = 'block';
                    }
                })
            },500)
        }


        // url封装
        function formate(url,dataObj){
            var start = true;
            var type = "GET";
            
            if(typeof url === 'object' && !(url instanceof Array)){
                dataObj = url;
                url = '';
                type = "POST";
            }

            // 2.参数拼接
            for(var key in dataObj){
                if(type === "GET"){
                    url += (start?"?":"&")+key+"="+dataObj[key];
                }else{
                    url += (start?"":"&")+key+"="+dataObj[key];
                }
                start = false;
            }
            return url;
        }

        // jsonp的ajax封装
        function ajax(options){
            options = Object.assign({
                method:'GET',
                _callback:function(){},
                url:'',
                dataObj:{},
                jsonpcallback:'callback',
            },options)

            // 1.请求方式为jsonp时
            if(options.method === "jsonp"){
                var script = document.createElement("script");
                script.src = formate(options.url,options.dataObj);
                document.body.appendChild(script);

                window[options.jsonpcallback] = function(data){
                    options._callback(data);
                }
                script.remove();
            }
            // 2.请求方式为get/post时
            else{
                var xhr = new XMLHttpRequest();

                xhr.open(options.method,options.method.toUpperCase() ==="GET" ? formate(options.url,options.dataObj) : options.url);

                if(options.method.toUpperCase()==="POST"){
                    xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
                }

                xhr.send(options.method.toUpperCase() ==="POST" ? formate(options.dataObj) : '');

                xhr.onreadystatechange = function(){
                    if(xhr.readyState===4&&/^2\d{2}$/.test(xhr.status)){
                        options._callback(xhr.responseText);
                    }
                }
            }
        }
    </script>
</body>
</html>